package com.fowo.api.service.handleWork;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.util.k3cloud.domain.Authentication;
import com.fowo.api.datainterface.util.k3cloud.domain.BillSave;
import com.fowo.api.entity.*;
import com.fowo.api.model.fine.use.voucher.FineUseVoucherBatchPushJinDieAction;
import com.fowo.api.service.handleWork.jindieEntity.jindieResult;
import com.fowo.api.service.handleWork.jindieEntity.jindieVoucher2;
import com.fowo.api.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class fineUseVoucherBatchPushJinDie implements FineUseVoucherBatchPushJinDieAction {

    @Resource
    private FineUseVoucherServiceImpl fineUseVoucherService;
    @Resource
    private BosAssistantdataDetailServiceImpl bosAssistantdataDetailService;
    @Resource
    private BdDepartmentServiceImpl departmentService;
    @Resource
    private BdRateServiceImpl bdRateService;
    @Resource
    private BdSupplierServiceImpl bdSupplierService;

    @Resource
    private BdCustomerServiceImpl customerService;
    @Resource
    private BdEmpinfoServiceImpl empinfoService;


    private static final Authentication auth=new Authentication("64e8964fb4af0d","Administrator","a@123456");

    private static final K3CloudTemplate k3loudTemplate=new K3CloudTemplate("http://121.225.97.82:8001/K3cloud/",auth);
    @Override
    public void run(List<Long> idList) throws Exception {

        //获取所有
        List<FineUseVoucher> list = fineUseVoucherService.list(Wrappers.<FineUseVoucher>query().lambda().in(FineUseVoucher::getId, idList));
        long yituisong = list.stream().filter(x -> x.getIsPublish().equals("是")).count();
        Assert.isTrue(yituisong==0,"已经推送,请重新选择");
        List<FineUseVoucher> list1 = fineUseVoucherService.list(Wrappers.<FineUseVoucher>query().lambda().in(FineUseVoucher::getId, idList));
        Assert.isTrue(list1.size()>0,"请选择要推送的凭证");
        FineUseVoucher fineUseVoucher = list.get(0);
        jindieVoucher2 jindieVoucher=new  jindieVoucher2();
        jindieVoucher.setIsAutoAdjustField("true");
        jindieVoucher2.ModelDTO  modelDTO=new jindieVoucher2.ModelDTO();
        modelDTO.setFvoucherid(0);
        //账簿
        jindieVoucher2.ModelDTO.FAccountBookIDDTO FAccountBookIDDTO=new  jindieVoucher2.ModelDTO.FAccountBookIDDTO();
        FAccountBookIDDTO.setFNumber("002");
        modelDTO.setFAccountBookID(FAccountBookIDDTO);
        modelDTO.setFDate(fineUseVoucher.getJsDate());//日期
        //凭证字
        jindieVoucher2.ModelDTO.FVOUCHERGROUPIDDTO FVOUCHERGROUPIDDTO=new jindieVoucher2.ModelDTO.FVOUCHERGROUPIDDTO();
        FVOUCHERGROUPIDDTO.setFNumber("PRE001");
        modelDTO.setFvouchergroupid(FVOUCHERGROUPIDDTO);
        modelDTO.setFvouchergroupno("1");
        modelDTO.setFDocumentStatus("Z");
        List<jindieVoucher2.ModelDTO.FEntityDTO> list2=new ArrayList<>();
        List<FineUseVoucher> lis=new ArrayList<>();

        String bizhong=bizhong(fineUseVoucher.getCurrency());
        BdRate one = bdRateService.getOne(Wrappers.<BdRate>query()
                .lambda().eq(BdRate::getCode, bizhong));
        Assert.notNull(one,"当前类别在汇率表中不存在!");
        BigDecimal bj=one.getRateNum();

        for(int i=0;i<list1.size();i++){
            FineUseVoucher fineUseVoucher1 = list1.get(i);
            pushJIndie(fineUseVoucher1,list2,bizhong,bj);
            fineUseVoucher1.setIsPublish("是");
            lis.add(fineUseVoucher1);
        }


        BigDecimal reduce = list.stream().map(x -> x.getMoney()).reduce(BigDecimal.ZERO, BigDecimal::add);

        BdSupplier DSupplier=null;
        BdEmpinfo DStaff=null;
        BdCustomer DCustom=null;
        //供应商
        if(StringUtils.isNotBlank(fineUseVoucher.getDsupplier())){
             DSupplier = bdSupplierService.getOne(Wrappers.<BdSupplier>query().lambda().eq(BdSupplier::getShortName, fineUseVoucher.getDsupplier()));
            Assert.notNull(DSupplier,fineUseVoucher.getDsupplier()+"供应商信息在金蝶中不存在！");
        }
        //员工
        if(StringUtils.isNotBlank(fineUseVoucher.getDstaff())){
             DStaff = empinfoService.getOne(Wrappers.<BdEmpinfo>query().lambda().eq(BdEmpinfo::getName, fineUseVoucher.getDstaff()));
            Assert.notNull(DStaff,fineUseVoucher.getDstaff()+"员工信息在金蝶中不存在！");
        }
        //客户
        if(StringUtils.isNotBlank(fineUseVoucher.getDcustom())){
             DCustom = customerService.getOne(Wrappers.<BdCustomer>query().lambda().eq(BdCustomer::getName, fineUseVoucher.getDcustom()));
            Assert.notNull(DCustom,fineUseVoucher.getDcustom()+"客户信息在金蝶中不存在！");
        }
        //物流商
        if(fineUseVoucher.getDlogistics()!=null){
//            BdCustomer one1 = customerService.getOne(Wrappers.<BdCustomer>query().lambda().eq(BdCustomer::getName, fineUseVoucher.getDlogistics()));
//            Assert.notNull(one1,fineUseVoucher.getDSupplier()+"物流商信息在金蝶中不存在！");
        }

        jindieVoucher2.ModelDTO.FEntityDTO entity1 = createEntity(fineUseVoucher.getFcreditAccountCode(),null,KeepOne(reduce,bj).doubleValue(),null,null,null,null,null,"",bizhong,reduce,DSupplier!=null?DSupplier.getNumber():null,null,DStaff!=null?DStaff.getNumber():null,DCustom!=null?DCustom.getNumber():null);
        list2.add(entity1);
        modelDTO.setFEntity(list2);
        jindieVoucher.setModel(modelDTO);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(jindieVoucher, false, false);
        BillSave billSave = new BillSave("GL_VOUCHER");
        billSave.setModel(stringObjectMap);
        String result = k3loudTemplate.executeBillSave(billSave, String.class);
        jindieResult jindieResult = JSONObject.parseObject(result, jindieResult.class);
        if(jindieResult.getResult().getResponseStatus().getIsSuccess().equals("true")){
            fineUseVoucherService.updateBatchById(lis);
        }else{
            Assert.isTrue(false,jindieResult.getResult().getResponseStatus().getErrors().get(0).getMessage());
        }
    }



    //推送
    public void pushJIndie(FineUseVoucher voById,List<jindieVoucher2.ModelDTO.FEntityDTO> list,String bizhong,BigDecimal bj){
//        String bizhong=bizhong(voById.getCurrency());
//        BdRate one = bdRateService.getOne(Wrappers.<BdRate>query()
//                .lambda().eq(BdRate::getCode, bizhong));
//        Assert.notNull(one,"当前类别在汇率表中不存在!");
//        BigDecimal bj=one.getRateNum();
        BdDepartment bumen=null;
        BosAssistantdataDetail shiyebu=null;
        BosAssistantdataDetail dianpu=null;
        if(voById.getDepartment()!=null){
            //获取部门的信息
             bumen = departmentService.getOne(Wrappers.<BdDepartment>query().lambda().eq(BdDepartment::getName, voById.getDepartment()));
            Assert.notNull(bumen,"部门信息在金蝶中不存在!");
        }
        if(voById.getDivision()!=null){
             shiyebu = bosAssistantdataDetailService.getOne(Wrappers.<BosAssistantdataDetail>query().lambda().eq(BosAssistantdataDetail::getDataValue, voById.getDivision()).eq(BosAssistantdataDetail::getFid,"64005285edcec5"));
            Assert.notNull(shiyebu,"事业部信息在金蝶中不存在!");
        }
        if(voById.getShop()!=null){
             dianpu = bosAssistantdataDetailService.getOne(Wrappers.<BosAssistantdataDetail>query().lambda().eq(BosAssistantdataDetail::getDataValue, voById.getShop()).eq(BosAssistantdataDetail::getFid,"6402dffc3586da"));
            Assert.notNull(dianpu,"店铺信息在金蝶中不存在!");
        }
        jindieVoucher2.ModelDTO.FEntityDTO entity = createEntity(voById.getFdebitAccountCode(),KeepOne(voById.getMoney(),bj).doubleValue(),null,shiyebu!=null?shiyebu.getNumber():null,bumen!=null?bumen.getNumber():null,dianpu!=null?dianpu.getNumber():null,null,null,dianpu!=null?dianpu.getDataValue()+"":"摘要",bizhong,voById.getMoney(),null,null,null,null);
        list.add(entity);

    };


    private static jindieVoucher2.ModelDTO.FEntityDTO createEntity(String kemu,
                                                                   Double jiefang,
                                                                   Double daifang,
                                                                   String shiyebu,
                                                                   String bumen,
                                                                   String dianpu,
                                                                   String gongchang,
                                                                   String code,
                                                                   String beizhu,
                                                                   String bizhong,
                                                                   BigDecimal benbi,
                                                                   String gongyingshang,
                                                                   String wuliushang,
                                                                   String yuangong,
                                                                   String kehu
    ){
        jindieVoucher2.ModelDTO.FEntityDTO fEntityDTO=new jindieVoucher2.ModelDTO.FEntityDTO();
        //科目编码
        jindieVoucher2.ModelDTO.FEntityDTO.FACCOUNTIDDTO FACCOUNTIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FACCOUNTIDDTO();
        FACCOUNTIDDTO.setFNumber(kemu);
        fEntityDTO.setFaccountid(FACCOUNTIDDTO);
        fEntityDTO.setFexplanation(beizhu);
        //币别
        jindieVoucher2.ModelDTO.FEntityDTO.FCURRENCYIDDTO  FCURRENCYIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FCURRENCYIDDTO();
        FCURRENCYIDDTO.setFNumber(bizhong);
        fEntityDTO.setFcurrencyid(FCURRENCYIDDTO);
        //汇率
        jindieVoucher2.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO FEXCHANGERATETYPEDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO();
        FEXCHANGERATETYPEDTO.setFNumber("HLTX01_SYS");
        fEntityDTO.setFexchangeratetype(FEXCHANGERATETYPEDTO);
        fEntityDTO.setFexchangerate(0.0);
        //借方金额
        fEntityDTO.setFdebit(jiefang);//
//        fEntityDTO.setFexchangerate(1.0);
        fEntityDTO.setFamountfor(benbi.doubleValue());//原币金额
//        fEntityDTO.setFAmount(jiefang!=null?jiefang:daifang);
        // 贷方金额
        fEntityDTO.setFcredit(daifang);
        jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO FDetailIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO();
        //事业部
        if(StringUtils.isNotBlank(shiyebu)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100003DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100003DTO();
            FDETAILIDFFLEX4DTO.setFNumber(shiyebu);
            FDetailIDDTO.setFDETAILID__FF100003(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //部门
        if(StringUtils.isNotBlank(bumen)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX5DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX5DTO();
            FDETAILIDFFLEX4DTO.setFNumber(bumen);
            FDetailIDDTO.setFDETAILID__FFLEX5(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //店铺
        if(StringUtils.isNotBlank(dianpu)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100007DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100007DTO();
            FDETAILIDFF100007DTO.setFNumber(dianpu);
            FDetailIDDTO.setFDETAILID__FF100007(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //供应商
        if(StringUtils.isNotBlank(gongyingshang)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX4DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX4DTO();
            FDETAILIDFF100007DTO.setFNumber(gongyingshang);//FDETAILIDFFLEX4DTO
            FDetailIDDTO.setFDETAILID__FFLEX4(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //物流商
        if(StringUtils.isNotBlank(wuliushang)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100006DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100006DTO();
            FDETAILIDFF100007DTO.setFNumber(wuliushang);//FDETAILIDFFLEX4DTO
            FDetailIDDTO.setFDETAILID__FF100006(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //员工
        if(StringUtils.isNotBlank(yuangong)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX7DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX7DTO();
            FDETAILIDFF100007DTO.setFNumber(yuangong);//FDETAILID__FFLEX7
            FDetailIDDTO.setFDETAILID__FFLEX7(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //客户
        if(StringUtils.isNotBlank(kehu)){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX6DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX6DTO();
            FDETAILIDFF100007DTO.setFNumber(kehu);//FDETAILIDFFLEX6DTO
            FDetailIDDTO.setFDETAILID__FFLEX6(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }

        return fEntityDTO;
    }

    //获取币种
    public  String bizhong(String s){
        String str=null;
        //金蝶的币种
        if(s.equals("USD")){
            str="PRE007";
        }else if(s.equals("CAD")){
            str="PRE008";
        }else if(s.equals("MXN")){
            str="PRE009";
        }else if(s.equals("EUR")){
            str="PRE003";
        }else if(s.equals("GBP")){
            str="PRE006";
        }else if(s.equals("CNY")){
            str="PRE001";
        }else{
            Assert.isTrue(false,"没有找到这个币种!");
        }
        return  str;
    }

    public BigDecimal KeepOne(BigDecimal bigDecimal, BigDecimal huilv){
        BigDecimal bigDecimal1 =bigDecimal.multiply(huilv).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bigDecimal1;
    }



}
